<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" @close="close" :close-on-click-modal="false" width="950px"
    append-to-body>
    <div class="form-box app-container">
      <el-form ref="form" :model="form" :inline="true" :rules="rules" label-width="100px"
        class="demo-ruleForm new_form_box">
        <el-form-item label="分销网名称" prop="retailName">
          <el-input v-model="form.retailName" placeholder="请输入分销网名称" />
        </el-form-item>
        <el-form-item label="关联店铺链接" prop="otherShopAddress">
          <el-input v-model="form.otherShopAddress" placeholder="请输入分销网关联店铺链接" />
        </el-form-item>
        <el-form-item label-width="60px" class="row" label="LOGO" prop="logo"
          :class="{ hiddenupload: logoImgList.length }">
          <el-input v-model="form.logo" v-show="false"></el-input>
          <el-upload class :action="uploadImgUrl" :file-list="logoImgList" :show-file-list="true"
            list-type="picture-card" :limit="1" accept="image/png, image/jpeg" :on-success="handleAvatarSuccess"
            :on-remove="handleAvatarRemove" :http-request="uploadImgs" :on-preview="imgPreview"
            :before-upload="beforeUploadImg">
            <div class="uploadbg">
              <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/icon/uploadbg.png" alt="">
              <br />
              <span>选择图片</span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label-width="60px" class="row" label="轮播图" prop="">
          <div class="table_box" style="box-shadow: none;border-radius: 4px;">

            <el-table border ref="table" :data="lunboList">

              <el-table-column label="图片" prop="img">
                <template slot-scope="scope">
                  <!-- <img style="height:32px" :src="scope.row.img" /> -->
                  <uploadImageOne :showSaoma="false" v-model="scope.row.img" @change="uploadChange($event, scope.row)">
                  </uploadImageOne>
                </template>
              </el-table-column>
              <el-table-column label="跳转链接" prop="link" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-input style="background-color: #fafafa; padding-left: 10px;" type="textarea" :rows="3"
                    placeholder="请输入跳转连接" v-model="scope.row.link"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="排序" prop="sort">
                <template slot-scope="scope">
                  <el-input @change="sortTable" style="background-color: #fafafa;padding-left: 10px;" type="text"
                    placeholder="请输入排序数字" v-model="scope.row.sort"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template slot-scope="scope">
                  <!-- <el-button icon="el-icon-edit" type="edit" @click="editItem(scope.row,scope.$index)">编辑</el-button> -->
                  <el-button icon="el-icon-delete" type="del" @click="delItem(scope.row, scope.$index)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-left:10px">
              <el-button icon="el-icon-plus" type="primary" size="small" @click="addLunbo"
                class="zdy-btn zdy-btn-refresh">添加轮播图</el-button>
            </div>

          </div>
        </el-form-item>
        <div class="center">
          <el-button @click="close()">取消</el-button>
          <el-button type="primary" @click="submitForm('form')" v-loading="loading">保存</el-button>
        </div>

      </el-form>
      <phoneImgListSettingAddEditDialog ref="phoneImgListSettingAddEditDialog" @editSuccess="editSuccess"
        @addSuccess="addSuccess"></phoneImgListSettingAddEditDialog>
    </div>
  </el-dialog>
</template>

<script>
import { updateotherShopAddress, addRprice, editRprice } from "@/api/info/rprice";
import { uploadFileFn } from "@/api/upload";
import phoneImgListSettingAddEditDialog from "../../../shopManage/shopSetting/pageSetting/setComponents/phoneImgListSettingAddEditDialog.vue";
import { t } from "@wangeditor/editor";
export default {
  name: "",
  components: { phoneImgListSettingAddEditDialog },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      title: "",
      uploadImgUrl: "",
      logoImgList: [],

      // 表单参数
      form: {
        retailKey: "",
        retailName: "",
        otherShopAddress: "",
        logo: "",
        lunboJSON: "",
      },
      lunboList: [
        {
          img: "",
          isOutLink: true,
          link: "",
          sort: "",
        },
      ],
      rules: {
        retailName: [
          { required: true, message: "请输入分销网名称", trigger: "change" },
        ],
      },
      type: "xhLunbo",
      editIndex: "",
      isEdit: false
    };
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo;
    },
  },
  created() {
    // this.headers = {
    //   Authorization: "Bearer " + getToken(),
    // };
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
  },
  methods: {
    // 打开弹窗
    open(flag, data) {
      console.log(data)
      this.lunboList = [
        {
          img: "",
          isOutLink: true,
          link: "",
          sort: "",
        },
      ];
      this.isEdit = false
      if (flag == "add") {
        this.title = "新增分销网";
      }
      if (flag == "edit") {
        this.isEdit = true
        this.title = "分销网设置";
        this.form.retailKey = data.retailKey;
        this.form.retailName = data.retailName;
        this.form.otherShopAddress = data.otherShopAddress;
        if (data.retailPageSet) {
          const setObj = JSON.parse(data.retailPageSet);
          this.form.logo = setObj.logo;
          this.logoImgList = []
          this.lunboList = [...setObj.lunboList];
          if (this.form.logo) {
            this.logoImgList = [
              {
                url: this.form.logo,
                name: "",
              },
            ];
          }
        }
      }

      this.dialogVisible = true;
    },

    // 重置
    reset() {
       this. form = {
          retailKey: "",
          retailName: "",
          otherShopAddress: "",
          logo: "",
          lunboJSON: "",
        }
      this.logoImgList = [];
      // this.$nextTick(() => {
      //   if (this.$refs.form) {
      //     this.$refs.form.resetFields();
      //   }
      // });
    },

    /** 查询详情进行回显 */
    handleUpdate(row) {
      this.form = row;
    },
    // 排序改变  重排表格顺序
    sortTable() {
      this.lunboList.sort((a, b) => a.sort - b.sort);
    },
    // 轮播图上传改变
    uploadChange(e, row) {
      // console.log("%c Line:148 🌭 e", "color:#ed9ec7", e);
      row.img = e;
    },
    // 打开增加轮播图的弹出
    addLunbo() {
      if (this.lunboList && this.lunboList.length >= 5) {
        return this.$message.error("最多只能添加5条！");
      }
      this.lunboList.push({
        img: "",
        isOutLink: true,
        link: "",
        sort: "",
      });
      // this.$refs.phoneImgListSettingAddEditDialog.open("add", "", this.type);
    },
    // 编辑轮播
    editItem(row, index) {
      console.log("%c Line:143 🎂 row", "color:#33a5ff", row);
      // 查看详情
      this.editIndex = index;
      this.$refs.phoneImgListSettingAddEditDialog.open("edit", row, this.type);
    },
    // 删除一个轮播
    delItem(row, i) {
      this.lunboList.splice(i, 1);
      // this.$message({
      //     type: "success",
      //     message: "删除成功!",
      //   });
    },
    // 轮播图编辑回调
    editSuccess(row) {
      const list = [...this.lunboList];
      list[this.editIndex] = { ...row };
      list.sort((a, b) => {
        return Number(a.sort || 0) - Number(b.sort || 0);
      });
      this.lunboList = list;
      this.$refs.table.doLayout();
    },
    // 轮播图新增回调
    addSuccess(row) {
      const list = [...this.lunboList];
      list.push(row);
      list.sort((a, b) => {
        return Number(a.sort || 0) - Number(b.sort || 0);
      });
      this.lunboList = list;
      this.$refs.table.doLayout();
    },
    // 提交
    submitForm(formName) {
      this.$refs["" + formName].validate((valid) => {
        if (valid) {
          // 处理页面配置的JSON
          const setObj = {
            logo: this.form.logo || "",
            lunboList: this.lunboList || [],
          };
          this.form.retailPageSet = JSON.stringify(setObj);
          if (this.isEdit) {
            // 编辑
            editRprice(this.form).then((res) => {
              this.$message.success(res.msg);
              this.$parent.getList();
              this.close();
            });
          } else {
            addRprice(this.form).then((res) => {
              this.$message.success(res.msg);
              this.$parent.getList();
              this.close();
            });

          }
        } else {
          this.$alert("请填写完整！");
        }
      });
    },
    imgPreview(url) {
      this.$viewerApi({
        images: [url],
      });
    },
    // logo图片移除
    handleAvatarRemove(response, file) {
      this.form.logo = "";
      this.logoImgList = [];
    },
    // logo图片上传成功
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        let url = res.data.filePath;
        let name = res.data.fileName;
        let param = {};
        param.url = url;
        param.name = name;
        this.logoImgList.push(param);
        this.form.logo = res.data.filePath;
      }
    },
    // 上传图片
    async uploadImgs(file) {
      // 获取压缩后的文件流
      let compreeBolb = await this.compressImage(file);
      //上传图片到后台
      try {
        // let uploadImg = await postUpload(formData);
        const resFile = await uploadFileFn(compreeBolb, this.userInfo.tenantId);
        const imgUrl = qiniu.imageMogr2(
          {
            strip: true, // 布尔值，是否去除图片中的元信息
            quality: 90, // 图片质量，取值范围1-100
            format: "jpg", // 新图的输出格式，取值范围：jpg，gif，png，webp等
          },
          resFile.key,
          resFile.domain
        );
        file.data = {
          filePath: decodeURIComponent(imgUrl),
        };
        file.code = 200;
        return file;
      } catch {
        file.code = 500;
        return file;
      }
    },
    // 限制图片大小
    beforeUploadImg(file) {
      if (file.size / 1024 / 1024 > 5) {
        this.$message.error("上传的图片不能超过5MB！请压缩后再传！");
        return false;
      } else {
        return true;
      }
    },

    close() {
      this.reset();
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="css">
.center {
  text-align: center;
}

.form-box {
  /* padding-top: 20px; */
  padding: 0;
  height: auto;
  min-height: initial;
  overflow-x: hidden;
}
</style>
